package com.qiku.service.impl;

import com.alibaba.fastjson.JSON;
import com.qiku.entity.LoginUser;
import com.qiku.entity.ResponseResult;
import com.qiku.entity.User;
import com.qiku.enums.AppHttpCodeEnum;
import com.qiku.exception.SystemException;
import com.qiku.service.LoginService;
import com.qiku.utils.BeanCopyUtils;
import com.qiku.utils.JwtUtils;
import com.qiku.vo.UserInfoVo;
import com.qiku.vo.UserLoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsServiceImpl userDetailsServiceImpl;
    @Override
    public ResponseResult login(User user) {
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(),user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //判断认证是否通过
        if(Objects.isNull(authenticate)){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        //获取userId的  生成token
        LoginUser loginUser = userDetailsServiceImpl.loadUserByUsername(user.getUserName());
        String userId = loginUser.getUser().getId().toString();
        String nickName = loginUser.getUser().getNickName();
        //工具类获取token
        String token = JwtUtils.getJwtToken(userId,nickName);
        //把用户信息存入redis
        redisTemplate.opsForValue().set("login-"+userId, loginUser);
        //把user转换成userInfoVo    jnn
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(loginUser.getUser(), UserInfoVo.class);
        //把token和userInfoVo放入userLoginVo中
        UserLoginVo userLoginVo = new UserLoginVo(token,userInfoVo);
        return ResponseResult.okResult(userLoginVo);
    }

    @Override
    public ResponseResult loginOut() {
        //获取token  解析userId
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        System.out.println("loginUser1111111:"+loginUser);
        //获取userId
        Long userId = loginUser.getUser().getId();
        //删除redis中的用户信息
        redisTemplate.delete("login-"+userId);
        return ResponseResult.okResult();
    }

}
